/*
 * 添加我的任务详情 
 */
import 'package:flutter/material.dart';
import './editInfo.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_auth/constants.dart';
import 'package:flutter_auth/common/picker_tool.dart'; // 日期组件
import 'package:flutter_auth/common/service.dart'; // 服务接口集合
import 'package:flutter_auth/constant/globals.dart' as globals;

class AddDetails extends StatefulWidget {
  State<StatefulWidget> createState() {
    return _AddDetailsState();
  }
}

class _AddDetailsState extends State<AddDetails> {
  final _formKey = GlobalKey<FormState>();
  var userInfo = globals.userInfo['data'];
  FocusNode _focusNodeFillDate = new FocusNode(); // 填写日期
  // 填写日期
  TextEditingController _fillDateController = new TextEditingController();
  List<dynamic> dataSource = []; // 数据源
  String date = ''; // 日期选择
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('创建日志'),
        leading: IconButton(
          icon: Icon(Icons.chevron_left, size: 30),
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
        actions: _actionsWidget(),
      ),
      body: _bodyWidget(),
      floatingActionButton: _saveWidget(),
    );
  }

  @override
  void initState() {
    /*
     * 监听完成时间 
     */
    _focusNodeFillDate.addListener(() {
      if (_focusNodeFillDate.hasFocus) {
        _focusNodeFillDate.unfocus();
        PickerTool.showDatePicker(
          context,
          dateType: DateType.YMD,
          title: "日期",
          value: date != '' ? DateTime.parse("$date") : new DateTime.now(),
          clickCallback: (var str, var time) {
            _fillDateController.text = str;
            setState(() {
              date = str;
            });
          },
        );
      }
      setState(() {});
    });
    super.initState();
  }

  List<Widget> _actionsWidget() {
    List<Widget> actions = [];
    if (dataSource.length != 0) {
      actions = [
        IconButton(
          icon: Icon(Icons.add_comment),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return EditInfo();
                },
                fullscreenDialog: true,
              ),
            ).then((juData) {
              if (juData != null) {
                _setDataSource(juData); // 设置数据源
              }
            });
          },
        )
      ];
    } else {
      actions = [];
    }
    return actions;
  }

  Widget _bodyWidget() {
    if (dataSource.length == 0) {
      return _addWidget();
    } else {
      return Column(
        children: <Widget>[
          _fileDateState(),
          new SizedBox(
            height: ScreenUtil().setHeight(40),
          ),
          Expanded(
            child: Scrollbar(
              child: ListView.separated(
                itemCount: dataSource.length,
                //列表项构造器
                itemBuilder: (BuildContext context, int index) {
                  final Axis slidableDirection = Axis.horizontal;
                  return _getSlidableWithLists(
                      context, index, slidableDirection);
                },
                //分割器构造器
                separatorBuilder: (context, index) => Divider(height: .0),
              ),
            ),
          ),
        ],
      );
    }
  }

  /*
   * 填写日期
   */
  Widget _fileDateState() {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: new Form(
        key: _formKey,
        child: TextFormField(
          keyboardType: TextInputType.number,
          controller: _fillDateController,
          focusNode: _focusNodeFillDate,
          //设置键盘类型
          decoration: InputDecoration(
            labelText: "填写时间",
          ),
          //验证对应任务
          validator: (v) {
            return v.trim().length > 0 ? null : "填写时间不能为空";
          },
        ),
      ),
    );
  }

  /*
   * 展示列表（可左右删除的列表）
   */
  Widget _getSlidableWithLists(
      BuildContext context, int index, Axis direction) {
    var item = dataSource[index];
    var projectName = dataSource[index]['projectName'];
    return Slidable(
      key: Key(item['key'].toString()),
      direction: direction,
      actionExtentRatio: 0.25,
      actionPane: SlidableDrawerActionPane(),
      child: ListTile(
        title: new Text("$projectName"),
        subtitle: new Text("${item['task']}"),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text('${item['completionDate']}'),
            Icon(Icons.chevron_right),
          ],
        ),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            item['index'] = index;
            return EditInfo(value: item);
          })).then((juData) {
            if (juData != null) {
              if (dataSource.length > 0 && juData.index != null) {
                var data = {
                  'task': juData.task,
                  'content': juData.content,
                  'completionDate': juData.completionDate,
                  'schedule': juData.schedule,
                  'projectName': juData.projectName,
                  'projectType': juData.projectType
                };
                setState(() {
                  dataSource[juData.index] = data;
                });
              }
            }
          });
        },
      ),
      secondaryActions: <Widget>[
        IconSlideAction(
          caption: '删除',
          color: Colors.red,
          icon: Icons.delete,
          onTap: () async {
            bool delete = await showDeleteConfirmDialog(); // 弹出删除确认框
            if (delete != null) {
              deleteItem(context, '删除成功', index);
            }
          },
        ),
      ],
    );
  }

  /*
   * 删除子集 
   */
  void deleteItem(BuildContext context, String text, index) {
    setState(() {
      dataSource.removeAt(index);
    });
  }

  /*
   * 弹出删除确认框 
   */
  Future<bool> showDeleteConfirmDialog() {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("您确定要删除?"),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
            ),
            FlatButton(
              child: Text("删除"),
              onPressed: () {
                //关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }

  /*
   * 保存模块 
   */
  Widget _saveWidget() {
    if (dataSource.length > 0) {
      return Container(
        margin: EdgeInsets.all(10.0), //容器外补白
        child: SizedBox(
          width: 100,
          height: 50,
          child: RaisedButton.icon(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(28),
            ),
            icon: Icon(
              Icons.save,
              color: Colors.white,
            ),
            color: kPrimaryColor,
            label: Text(
              "保存",
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.0,
                height: 1.2,
              ),
            ),
            onPressed: () {
              _focusNodeFillDate.unfocus();
              if (_formKey.currentState.validate()) {
                addLog({
                  'userId': userInfo['id'],
                  'date': date,
                  'list': dataSource
                }).then((result) {
                  Navigator.pop(context, true);
                });
              }
            },
          ),
        ),
      );
    }
  }

  /*
   * 添加模块 
   */
  Widget _addWidget() {
    return Container(
      margin: EdgeInsets.all(20.0), //容器外补白
      alignment: Alignment.center,
      child: SizedBox(
        width: 200,
        height: 60,
        child: RaisedButton.icon(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(28),
          ),
          icon: Icon(
            Icons.add,
            color: Colors.white,
          ),
          color: Colors.green,
          label: Text(
            "创建",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18.0,
              height: 1.2,
            ),
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return EditInfo();
                },
                fullscreenDialog: true,
              ),
            ).then((juData) {
              if (juData != null) {
                _setDataSource(juData); // 设置数据源
              }
            });
          },
        ),
      ),
    );
  }

  /*
   * 设置数据源 
   */
  void _setDataSource(var juData) {
    var data = {
      'task': juData.task,
      'content': juData.content,
      'completionDate': juData.completionDate,
      'schedule': juData.schedule,
      'projectName': juData.projectName,
      'projectType': juData.projectType
    };
    setState(() {
      dataSource.add(data);
    });
  }
}
